package com.fcy.security.aes.another;

import java.security.Key;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * 受到美国的出口限制
 * 抛出：java.security.InvalidKeyException: Illegal key size or default parameters
 * 解决方法： Oracle在其官方网站上提供了无政策限制权限文件（Unlimited Strength Jurisdiction Policy Files），只需要将其部署在JRE环境中，就可以解决限制问题。
 * @author fangchengyan
 *
 */
public class AESCoder {
	
	private static String key = "42fb083e5be4c6af74dd378f9752dabf011c17e7d8178663ce643b2e4c1efd13";
	//[66, -5, 8, 62, 91, -28, -58, -81, 116, -35, 55, -113, -105, 82, -38, -65, 1, 28, 23, -25, -40, 23, -122, 99, -50, 100, 59, 46, 76, 30, -3, 19]

	private static final String KEY_ALGORITHM = "AES";
	private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	private static Key toKey(String key) throws Exception {
		SecretKey secretKey = new SecretKeySpec(decodeHex(key), KEY_ALGORITHM);
		return secretKey;
	}
	
	/**
	 * 生成密钥
	 */
	private static String initKey() throws Exception {
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		kg.init(256);
		SecretKey secretKey = kg.generateKey();
		byte[] kd = secretKey.getEncoded();
		System.out.println("52: " + Arrays.toString(kd));
		return encodeHex(kd);
	}
	
	private static byte[] decodeHex(String data) throws DecoderException {
		return Hex.decodeHex(data.toCharArray());
	}
	
	private static String encodeHex(byte[] data) throws DecoderException {
		return new String(Hex.encodeHex(data));
	}
	/**
	 * 解密
	 */
	private static String decrypt(String data) throws Exception {
		Key k = toKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, k);
		return encodeHex(cipher.doFinal(data.getBytes()));
	}
	
	/**
	 * 加密
	 */
	private static String encrypt(String data) throws Exception {
		Key k = toKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, k);
		return encodeHex(cipher.doFinal(data.getBytes()));
	}
	
	public static void main(String[] args) throws Exception {
		String kd = initKey();
		System.out.println(kd);
		System.out.println(Arrays.toString(decodeHex(kd)));
		
		String data = "haha";
		String en = encrypt(data);
		System.out.println(en);
		System.out.println(decrypt(en));
	}
	
	
}
